package com.inter.controller.travis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.open.request.RequestOpenPackage;
import com.inter.entity.newinterentity.open.request.RequestOpenPackageData;
import com.inter.entity.newinterentity.open.request.RequestOpenPackageTradeData;
import com.inter.entity.newinterentity.open.response.ResponseOpenPackage;
import com.inter.entity.newinterentity.open.response.ResponseOpenPackageData;
import com.inter.entity.newinterentity.open.response.ResponseOpenPackageTradeData;
import com.inter.entity.newpojo.Constant;
import com.inter.entity.newrequest.openpackages.request.RequestOpenPackagesNew;
import com.inter.entity.newrequest.openpackages.response.ResponseOpenPackagesNew;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.utils.HttpUtil;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * api:开通流量套餐
 * <p>
 * 条件：order_id
 * <p>
 * 返回开通结果
 *
 * @author lm
 * @date 2019/07/23
 */
@RestController
@Api(description = "Open Data")
public class OpenDataController {

    private static Logger logger = Logger.getLogger(OpenDataController.class);

    @Autowired
    SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;

    @CrossOrigin
    @RequestMapping(value = "/openData", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "Open Data", response = ResponseOpenPackage.class)
    public String openData(@ApiParam @RequestBody RequestOpenPackage request) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();

        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();

        String requestStr = JSON.toJSONString(request);

        if (requestStr == null) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求报文是：" + requestStr);
            RequestOpenPackage requestPackage = JSONArray.parseObject(requestStr, RequestOpenPackage.class);
            String requestSign = requestPackage.getSign();

            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestOpenPackageData requestData = requestPackage.getData();

                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {

                    String partnerCode = requestData.getPartnerCode();
                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    RequestOpenPackageTradeData tradeData = requestData.getTradeData();

                    //lang为空或者为null时，默认为cn
                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(lang) || tradeData == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String orderId = tradeData.getOrderId();
                        if (StringUtils.isBlank(orderId)) {
                            logger.info("请求报文不合法:orderId参数不能为空！");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;

                        } else {

                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);

                            if (!requestSign.equalsIgnoreCase(sign)) {

                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;

                            } else {

                                //签名验证通过
                                RequestOpenPackagesNew realTimeNew = new RequestOpenPackagesNew();
                                realTimeNew.setOrderId(orderId);
                                realTimeNew.setPartnerCode(partnerCode);
                                realTimeNew.setSecret(secret);

                                String req = JSON.toJSONString(realTimeNew);
                                //logger.info("请求北京的接口请求报文：" + req);
                                String url1 = "http://localhost:8085/iot" + Constant.iot_openPackage;
                                // 发送post请求，并接收返回结果
                                String returns = HttpUtil.httpPost(url1, req);
                                //logger.info("北京回复的下发接口响应报文：" + returns);
                                ResponseOpenPackagesNew res = JSONArray.parseObject(returns, ResponseOpenPackagesNew.class);


                                ResponseOpenPackage response = new ResponseOpenPackage();

                                ResponseOpenPackageData data = new ResponseOpenPackageData();

                                if (res != null) {

                                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(res.getRetCode())) {

                                        //开通成功
                                        ResponseOpenPackageTradeData resTra = new ResponseOpenPackageTradeData();
                                        resTra.setOrderId(orderId);
                                        resTra.setOrderStartDate(res.getOrderStartDate());
                                        resTra.setOrderExpireDate(res.getOrderExpireDate());

                                        data.setTradeData(resTra);
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeRstCode(1000);

                                        if (lang.equals("en")) {
                                            data.setTradeRstMessage("success");
                                        } else {
                                            data.setTradeRstMessage("成功");
                                        }

                                        response.setData(data);
                                        response.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        jsonString = JSON.toJSONString(response);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;


                                    } else {
                                        //返回的代码不是0000，就是未成功开通，肯定有原因

                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeRstCode(Integer.parseInt(res.getRetCode()));

                                        if (lang.equals("en")) {
                                            if (res.getRetCode().equals("0025")) {
                                                data.setTradeRstMessage("The opening sign is illegal and cannot be opened ！");
                                            } else if (res.getRetCode().equals("0026")) {
                                                data.setTradeRstMessage("Failure of Opening Flow Data ！");
                                            } else if (res.getRetCode().equals("0027")) {
                                                data.setTradeRstMessage("This orderId does not exist ！");
                                            } else if (res.getRetCode().equals("0028")) {
                                                data.setTradeRstMessage("Only orders that have been ordered are allowed to be opened ！");
                                            } else if (res.getRetCode().equals("0029")) {
                                                data.setTradeRstMessage("orderId cannot be empty ！");
                                            } else if (res.getRetCode().equals("0105")) {
                                                data.setTradeRstMessage("OTA order does not support interface open ！");
                                            } else {
                                                data.setTradeRstMessage("Failure of Opening Flow Data ！");
                                            }
                                        } else {
                                            data.setTradeRstMessage(res.getResultInfo());
                                        }

                                        response.setData(data);
                                        response.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        jsonString = JSON.toJSONString(response);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;

                                    }


                                } else {

                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeRstCode(9998);
                                    if (lang.equals("en")) {
                                        data.setTradeRstMessage("Interface response message is empty ！");
                                    } else {
                                        data.setTradeRstMessage("接口响应报文为空！");
                                    }

                                    response.setData(data);
                                    response.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    jsonString = JSON.toJSONString(response);
                                    logger.info("响应报文：" + jsonString);
                                    return jsonString;
                                }

                            }
                        }
                    }
                }
            }
        }
    }

}
